// stores/authStore.js
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import personalInfoService from '../services/personalInfoService'; // 确保路径正确

export const useAuthStore = defineStore('auth', () => {
  // --- State ---

  const initializeUser = () => {
    const storedUser = localStorage.getItem('user');
    if (storedUser && storedUser !== 'undefined') {
      try {
        const parsedUser = JSON.parse(storedUser);
        // 【新增】: 从 localStorage 加载时也确保 avatar 字段的存在
        if (parsedUser.avatarUrl && !parsedUser.avatar) {
          parsedUser.avatar = parsedUser.avatarUrl;
        }
        return parsedUser;
      } catch (error) {
        console.error('Failed to parse user from localStorage:', error);
        return null;
      }
    }
    return null;
  };

  const token = ref(localStorage.getItem('token') || null);
  const user = ref(initializeUser());

  // --- Getters ---
  const isAuthenticated = computed(() => !!token.value);

  // --- Actions ---

  function setUser(userData) {
    if (userData && userData.token) {
      token.value = userData.token;
      localStorage.setItem('token', userData.token);
    } else {
      token.value = null;
      localStorage.removeItem('token');
    }

    if (userData && userData.user) {
      // 【核心修改】: 在设置 user.value 之前，确保 avatar 字段存在
      // 后端返回的是 avatarUrl，而前端组件需要 avatar
      const userToSet = { ...userData.user }; // 复制一份，避免直接修改原始对象
      if (userToSet.avatarUrl && !userToSet.avatar) {
        userToSet.avatar = userToSet.avatarUrl;
      }

      user.value = userToSet; // 使用处理后的 userToSet
      localStorage.setItem('user', JSON.stringify(userToSet)); // 存储处理后的对象
    } else {
      user.value = null;
      localStorage.removeItem('user');
    }
  }

  async function fetchUserProfile() {
    if (!token.value) {
      user.value = null;
      localStorage.removeItem('user');
      return;
    }
    try {
      const profileData = await personalInfoService.getPersonalInfo();
      if (profileData) {
        const updatedUser = {
          ...user.value,
          username: profileData.username,
          name: profileData.name,
          email: profileData.email,
          phone: profileData.phone,
          department: profileData.department,
          avatar: profileData.avatarUrl, // 确保 avatar 字段被正确设置
        };
        user.value = updatedUser;
        localStorage.setItem('user', JSON.stringify(updatedUser));
        console.log("AuthStore: 用户个人资料已更新", user.value);
      }
    } catch (error) {
      console.error('Failed to fetch user profile:', error);
      // logout(); // 考虑是否需要在获取失败时登出
    }
  }

  function logout() {
    token.value = null;
    user.value = null;
    localStorage.removeItem('token');
    localStorage.removeItem('user');
  }

  return { token, user, isAuthenticated, setUser, logout, fetchUserProfile };
});